<template>
  <div class="p-2 modal_main">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" size="small" label-width="80">
            <el-form-item label="模型名" prop="modelName">
              <el-input v-model="queryParams.modelName" placeholder="请输入模型名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="模型分类" prop="modelType">
              <el-input v-model="queryParams.modelType" placeholder="请输入模型分类" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker
              style="width: 240px"
                v-model="dateRangeCreateTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="业务场景" prop="businessScenarios">
              <el-input v-model="queryParams.businessScenarios" placeholder="请输入业务场景" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item style="padding-left: 80px">
              <el-button size="small" type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button size="small" icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button size="small" v-hasPermi="['system:oss:upload']" type="primary" plain icon="Plus" @click="handleFile">新增模型</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-tooltip class="item" content="功能建设中..." placement="top-start">
              <el-button size="small" v-hasPermi="['system:oss:upload']" type="primary" plain icon="Upload">批量上传</el-button>
            </el-tooltip>
          </el-col>
          <el-col :span="1.5">
            <el-button size="small" v-hasPermi="['system:oss:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">
              删除
            </el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:oss:edit']"
              :type="previewListResource ? 'danger' : 'warning'"
              plain
              @click="handlePreviewListResource(!previewListResource)"
              >预览开关 : {{ previewListResource ? '禁用' : '启用' }}</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:oss:list']" type="info" plain icon="Operation" @click="handleOssConfig">配置管理</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        v-if="showTable"
        v-loading="loading"
        :data="ossList"
        :header-cell-class-name="handleHeaderClass"
        @selection-change="handleSelectionChange"
        @header-click="handleHeaderCLick"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="对象存储主键" align="center" prop="modelId" />
        <el-table-column label="模型名" align="center" prop="modelName" width="180" />
        <el-table-column label="模型分类" align="center" prop="modelType" />
        <el-table-column label="适用机型" align="center" prop="applicableModels" />
        <el-table-column label="机型系列" align="center" prop="modelSeries" />
        <el-table-column label="载荷情况" align="center" prop="loadConditions" width="200" />
        <el-table-column label="模型范围" align="center" prop="modelScope" />
        <el-table-column label="业务场景" align="center" prop="businessScenarios" />
        <el-table-column label="来源方式" align="center" prop="sourceMethods" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" >
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上传人" align="center" prop="createByName" />
        <el-table-column label="操作" align="center" width="210">
          <template #default="scope">
            <el-tooltip content="备注" placement="top">
              <el-button size="small" v-hasPermi="['system:oss:download']" link type="primary" icon="View" @click="handleDetail(scope.row)">备注</el-button>
            </el-tooltip>
            <el-tooltip content="下载" placement="top">
              <el-button size="small" v-hasPermi="['system:oss:download']" link type="primary" icon="Download" @click="handleDownload(scope.row)">下载</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button size="small" v-hasPermi="['system:oss:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagenation">
        <el-pagination
          v-show="total > 0"
          layout="prev, pager, next,jumper"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          :total="total"
          @pagination="handleCurrentChange"
        />
      </div>
      <!-- <pagination size="small" v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" /> -->
    </el-card>
    <!-- 添加或修改OSS对象存储对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="780px" append-to-body>
      <el-form ref="ossFormRef" :model="form" :rules="rules" label-width="80px" inline size="small">
        <el-form-item label="模型名称" style="width: 672px" prop="modelName">
          <el-input placeholder="默认为上传文件的文件名" v-model="form.modelName" />
        </el-form-item>
        <el-form-item label="适用机型" prop="applicableModels">
          <el-select v-model="form.applicableModels">
            <el-option label="ARJ21" value="ARJ21"></el-option>
            <el-option label="C919" value="C919"></el-option>
            <el-option label="C929" value="C929"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="机型系列" prop="modelSeries">
          <el-select v-model="form.modelSeries">
            <el-option label="基本型" value="基本型"></el-option>
            <el-option label="衍生型" value="衍生型"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="载荷情况" prop="loadConditions">
          <el-select v-model="form.loadConditions">
            <el-option label="全机内力载荷" value="全机内力载荷"></el-option>
            <el-option label="全机内力载荷(叠加温度场)" value="全机内力载荷(叠加温度场)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模型范围" prop="modelScope">
          <el-select v-model="form.modelScope">
            <el-option label="机身机翼" value="机身机翼"></el-option>
            <el-option label="垂尾" value="垂尾"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务场景" prop="businessScenarios">
          <el-select v-model="form.businessScenarios">
            <el-option label="结构分析" value="结构分析"></el-option>
            <el-option label="流体分析" value="流体分析"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="来源方式" prop="sourceMethods">
          <el-select v-model="form.sourceMethods">
            <el-option label="个人上传" value="个人上传"></el-option>
            <el-option label="离线导入" value="离线导入"></el-option>
            <el-option label="接口同步" value="接口同步"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模型描述" style="width: 672px" prop="modelDescription">
          <el-input type="textarea" rows="2" resize="none" v-model="form.modelDescription" />
        </el-form-item>
        <el-form-item label="上传文件" prop="file">
          <el-upload
            :before-upload="handleBeforeUpload"
            @change="handleChange"
            :on-remove="handleRemove"
            :file-list="fileList"
            :show-file-list="true"
            :auto-upload="false"
            :multiple="false"
            :limit="1"
            action="#"
          >
            <el-button size="small" type="primary">选取文件</el-button>
            <div class="el-upload__tip">模型文件大小超过1GB,请走离线方式</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button size="small" @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="detaiDialogShow" title="备注" width="500px" append-to-body>
      <div>{{ detailInfo }}</div>
    </el-dialog>
  </div>
</template>

<script setup name="Oss" lang="ts">
import { listOss, delOss  } from '@/api/system/oss';
import { OssForm, OssQuery, OssVO } from '@/api/system/oss/types';
import axios from 'axios';
import { getToken } from '@/utils/auth';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const ossList = ref<OssVO[]>([]);
const showTable = ref(true);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const type = ref(0);
const previewListResource = ref(true);
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);
const fileList = ref<any[]>([]);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const submitFile = ref(null);
// 默认排序
const defaultSort = ref({ prop: 'createTime', order: 'descending' });

const ossFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();
const detaiDialogShow = ref(false);
const detailInfo = ref('');

const initFormData = {
  file: undefined,
  modelName: '',
  applicableModels: 'ARJ21',
  modelSeries: '基本型',
  loadConditions: '全机内力载荷',
  modelScope: '机身机翼',
  businessScenarios: '结构分析',
  modelDescription: '',
  sourceMethods: '个人上传',
  modelType: ''
};
const data = reactive<PageData<OssForm, OssQuery>>({
  form: { ...initFormData },
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    fileName: '',
    modelName: '',
    modelType: '',
    fileSuffix: '',
    createTime: '',
    businessScenarios: '',
    orderByColumn: defaultSort.value.prop,
    isAsc: defaultSort.value.order
  },
  rules: {
    // modelName: [{ required: true, message: '模型名不能为空', trigger: 'blur' }],
    applicableModels: [{ required: true, message: '适用机型不能为空', trigger: 'blur' }],
    modelSeries: [{ required: true, message: '机型系列不能为空', trigger: 'blur' }],
    loadConditions: [{ required: true, message: '载荷情况不能为空', trigger: 'blur' }],
    modelScope: [{ required: true, message: '模型范围不能为空', trigger: 'blur' }],
    businessScenarios: [{ required: true, message: '业务场景不能为空', trigger: 'blur' }],
    sourceMethods: [{ required: true, message: '来源方式不能为空', trigger: 'blur' }],
    file: [{ required: true, message: '上传文件不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
const handleCurrentChange = (number) => {
  queryParams.value.pageNum = number;
  getList();
};
// 查看详情
const handleDetail = (data) => {
  detaiDialogShow.value= true;
  detailInfo.value = data.modelDescription;
};
// 上传前校检格式和大小
const handleBeforeUpload = (file: any) => {
  // 校检文件大小
  const isLt = file.size / 1024 / 1024 < 1024;
  if (!isLt) {
    proxy?.$modal.msgError(`上传文件大小不能超过 1024 MB!`);
    return false;
  }
  return true;
};
const handleRemove = (file: any) => {
  fileList.value = [];
  form.value.file = null;
  form.value.modelName = '';
};
const handleChange = (file: any) => {
  submitFile.value = file;
  form.value.file = file;
  form.value.modelName = file.name;
  ossFormRef.value.validate();
};

/** 查询模型列表 */
const getList = async () => {
  loading.value = true;
  const res = await proxy?.getConfigKey('sys.oss.previewListResource');
  previewListResource.value = res?.data === undefined ? true : res.data === 'true';
  const response = await listOss(proxy?.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime'));
  ossList.value = response.rows;
  total.value = response.total;
  loading.value = false;
  showTable.value = true;
};
/** 取消按钮 */
function cancel() {
  dialog.visible = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = { ...initFormData };
  ossFormRef.value?.resetFields();
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  showTable.value = false;
  dateRangeCreateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.orderByColumn = defaultSort.value.prop;
  queryParams.value.isAsc = defaultSort.value.order;
  handleQuery();
}
/** 选择条数  */
function handleSelectionChange(selection: OssVO[]) {
  ids.value = selection.map((item) => item.modelId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 设置列的排序为我们自定义的排序 */
const handleHeaderClass = ({ column }: any): any => {
  column.order = column.multiOrder;
};
/** 点击表头进行排序 */
const handleHeaderCLick = (column: any) => {
  if (column.sortable !== 'custom') {
    return;
  }
  switch (column.multiOrder) {
    case 'descending':
      column.multiOrder = 'ascending';
      break;
    case 'ascending':
      column.multiOrder = '';
      break;
    default:
      column.multiOrder = 'descending';
      break;
  }
  handleOrderChange(column.property, column.multiOrder);
};
const handleOrderChange = (prop: string, order: string) => {
  let orderByArr = queryParams.value.orderByColumn ? queryParams.value.orderByColumn.split(',') : [];
  let isAscArr = queryParams.value.isAsc ? queryParams.value.isAsc.split(',') : [];
  let propIndex = orderByArr.indexOf(prop);
  if (propIndex !== -1) {
    if (order) {
      //排序里已存在 只修改排序
      isAscArr[propIndex] = order;
    } else {
      //如果order为null 则删除排序字段和属性
      isAscArr.splice(propIndex, 1); //删除排序
      orderByArr.splice(propIndex, 1); //删除属性
    }
  } else {
    //排序里不存在则新增排序
    orderByArr.push(prop);
    isAscArr.push(order);
  }
  //合并排序
  queryParams.value.orderByColumn = orderByArr.join(',');
  queryParams.value.isAsc = isAscArr.join(',');
  getList();
};
/** 新增模型 */
const handleFile = () => {
  reset();
  type.value = 0;
  dialog.visible = true;
  dialog.title = '新增模型';
  fileList.value = [];
  // 设置表单默认值
  if (ossList.value.length > 0) {
    form.value.applicableModels = ossList.value[0].applicableModels;
    form.value.modelSeries = ossList.value[0].modelSeries;
    form.value.loadConditions = ossList.value[0].loadConditions;
    form.value.modelScope = ossList.value[0].modelScope;
    form.value.businessScenarios = ossList.value[0].businessScenarios;
    form.value.sourceMethods = ossList.value[0].sourceMethods;
  }
};
/** 提交按钮 */
const submitForm = async () => {
  ossFormRef.value.validate((valid: any) => {
    if (!valid) {
      return false;
    } else {
      const formData = new FormData();
      const metadata = form.value;
      metadata.modelType = metadata.file?.name.slice(metadata.file?.name.lastIndexOf('.'));
      delete metadata.file;
      formData.append('file', submitFile.value.raw);
      formData.append('modelName', metadata?.modelName);
      formData.append('applicableModels', metadata?.applicableModels);
      formData.append('modelSeries', metadata?.modelSeries);
      formData.append('loadConditions', metadata?.loadConditions);
      formData.append('modelScope', metadata?.modelScope);
      formData.append('businessScenarios', metadata?.businessScenarios);
      formData.append('modelDescription', metadata?.modelDescription);
      formData.append('sourceMethods', metadata?.sourceMethods);
      formData.append('modelType', metadata?.modelType);
      let VITE_APP_BASE_API = '/dev-api';
      if (import.meta.env.MODE === 'production') {
        VITE_APP_BASE_API = '/prod-api';
      }
      axios
        .post(`${VITE_APP_BASE_API}/model/save`, formData, {
          headers: { 'Content-Type': 'multipart/form-data', 'Authorization': 'Bearer ' + getToken() }
        })
        .then((res) => {
          dialog.visible = false;
          fileList.value = [];
          getList();
        });
    }
  });
};
/** 下载按钮操作 */
const handleDownload = (row: OssVO) => {
  proxy?.$download.oss(row.modelId);
};
/** 删除按钮操作 */
const handleDelete = async (row?: OssVO) => {
  const modelIds = row?.modelId || ids.value;
  await proxy?.$modal.confirm('是否确认删除模型名为"' + row?.modelName + '"的数据项?');
  loading.value = true;
  await delOss(modelIds).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
.modal_main{
  height: calc(100vh - 84px);
  overflow: auto;
}
.pagenation {
  display: flex;
  justify-content: end;
  margin-top: 10px;
}
:deep(.el-upload) {
  display: block;
}
</style>
